package com.sh.d1.gatewayserver;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 内部服务器消息处理器
 */
public class InternalServerMsgHandler extends SimpleChannelInboundHandler<Object> {
    /**
     * 日志对象
     */
    static private final Logger LOGGER = LoggerFactory.getLogger(InternalServerMsgHandler.class);

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
        ChannelPipeline pl = ctx.pipeline();
        if (null == pl.get(CheckDuplicateLoginHander.class)) {
            pl.addBefore(
                    ctx.name(),
                    CheckDuplicateLoginHander.class.getName(),
                    new CheckDuplicateLoginHander()
            );
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msgObj) {
        if (!(msgObj instanceof BinaryWebSocketFrame)) {
            return;
        }

        BinaryWebSocketFrame inputFrame = (BinaryWebSocketFrame) msgObj;
        ByteBuf oldByteBuf = inputFrame.content();

        // 读掉消息长度
        oldByteBuf.readShort();

        // 读取网关服务器 Id
        int gatewayServerId = oldByteBuf.readInt();
        // 读取会话 Id
        int sessionId = oldByteBuf.readInt();
        // 读取用户 Id
        int fromUserId = oldByteBuf.readInt();
        //消息编码
        int msgCode = oldByteBuf.readShort();

        LOGGER.info(
                "收到 gameServer 返回的消息, sessionId = {},fromUserId = {},msgCode = {}",
                sessionId,
                fromUserId,
                msgCode
        );


        // 获取客户端信道
        Channel clientCh = ClientChannelGroup.getBySessionId(sessionId);

        if (null == clientCh ||
                !clientCh.isOpen()) {
            return;
        }


        ByteBuf newByteBuf = ctx.alloc().buffer();

        newByteBuf.writeShort(0);   //0占位
        newByteBuf.writeShort(msgCode);

        oldByteBuf.readBytes(newByteBuf, oldByteBuf.readableBytes());
        newByteBuf.setShort(0,  //覆盖0 1两个字节 更新消息长度
                oldByteBuf.readableBytes());

        BinaryWebSocketFrame outputFrame = new BinaryWebSocketFrame(newByteBuf);
        clientCh.writeAndFlush(outputFrame);
    }
}
